package com.young.interceptor;

import com.young.annotation.LimitIntercept;
import com.young.constants.RedisConstant;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit;

public class LimitInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public LimitInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{
        if (!(handler instanceof HandlerMethod)){
            return false;
        }
        HandlerMethod method=(HandlerMethod) handler;
        LimitIntercept limitIntercept = ((HandlerMethod) handler).getMethodAnnotation(LimitIntercept.class);
        if (limitIntercept==null||!limitIntercept.required()){
            return true;
        }
        int maxCount=limitIntercept.maxCount();
        int waitTime=limitIntercept.waitTime();
        //当未过期时
        if (stringRedisTemplate.hasKey(RedisConstant.LIMIT_KEY)){
            Integer count = Integer.valueOf(stringRedisTemplate.opsForValue().get(RedisConstant.LIMIT_KEY));
            if (count<=0){
                System.out.println("限流了=============");
                return false;
            }
            //减少次数
            stringRedisTemplate.opsForValue().decrement(RedisConstant.LIMIT_KEY);
            return true;
        }
        //设置到redis中
        stringRedisTemplate.opsForValue().set(RedisConstant.LIMIT_KEY,maxCount+"",waitTime, TimeUnit.SECONDS);
        return true;
    }
}
